package com.neudu.yyzx_service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neudu.yyzx_service.common.JSONReturn;
import com.neudu.yyzx_service.pojo.Bed;
import com.neudu.yyzx_service.pojo.Customer;
import com.neudu.yyzx_service.pojo.BedDetails;
import com.neudu.yyzx_service.service.BedService;
import com.neudu.yyzx_service.service.CustomerService;
import com.neudu.yyzx_service.service.BedDetailsService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/beds")
public class BedController {

    private static final Logger logger = LoggerFactory.getLogger(BedController.class);

    @Resource
    private JSONReturn jsonReturn;
    @Resource
    private BedService bedService;
    @Resource
    private BedDetailsService bedDetailsService;
    @Resource
    private CustomerService customerService;

    // 获取所有床位
    @GetMapping
    public ResponseEntity<List<Bed>> getAllBeds() {
        try {
            List<Bed> beds = bedService.list();
            logger.info("返回的床位数据：{}", beds);
            return ResponseEntity.ok(beds);
        } catch (Exception e) {
            logger.error("获取所有床位时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Bed> getBedById(@PathVariable Long id) {
        try {
            Bed bed = bedService.getById(id); // 使用 MyBatis-Plus 提供的 getById 方法
            if (bed == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(bed);
        } catch (Exception e) {
            logger.error("根据 ID 获取床位时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    // 新增床位
    @PostMapping
    public ResponseEntity<?> createBed(@RequestBody Bed bed) {
        try {
            logger.info("接收到的 bed 对象：{}", bed);
            bedService.save(bed);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("新增床位时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @PostMapping("/checkIn/{bedId}")
    public ResponseEntity<?> checkIn(@PathVariable Long bedId, @RequestBody BedDetails bedDetails) {
        try {
            Bed bed = bedService.getById(bedId);
            if (bed == null) {
                return ResponseEntity.badRequest().body("未找到该床位");
            }
            if (!"free".equals(bed.getBedStatus())) {
                return ResponseEntity.badRequest().body("该床位已被入住");
            }
            bedDetails.setBedId(bedId);
            bedDetails.setIsDeleted(0); // 标记为未删除
            bedDetailsService.save(bedDetails);
            bed.setBedStatus("occupied");
            bedService.updateById(bed);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("床位入住操作时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    // 退住操作
    @PostMapping("/checkOut/{bedId}")
    public ResponseEntity<?> checkOut(@PathVariable Long bedId) {
        try {
            Bed bed = bedService.getById(bedId);
            if (bed == null) {
                return ResponseEntity.badRequest().body("未找到该床位");
            }
            if (!"occupied".equals(bed.getBedStatus())) {
                return ResponseEntity.badRequest().body("该床位未被入住");
            }
            // 查询当前床位未删除的入住记录
            LambdaQueryWrapper<BedDetails> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BedDetails::getBedId, bedId).eq(BedDetails::getIsDeleted, 0);
            BedDetails bedDetails = bedDetailsService.getOne(queryWrapper);
            if (bedDetails != null) {
                bedDetails.setEndDate(new Date()); // 设置退住日期为当前时间
                bedDetails.setIsDeleted(1); // 标记为已删除
                bedDetailsService.updateById(bedDetails);
            }
            bed.setBedStatus("free");
            bedService.updateById(bed);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("床位退住操作时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    // 获取床位详情（包含入住和退住日期）
    @GetMapping("/details/{bedId}")
    public ResponseEntity<List<Map<String, Object>>> getBedDetails(@PathVariable Long bedId) {
        try {
            LambdaQueryWrapper<BedDetails> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BedDetails::getBedId, bedId);
            List<BedDetails> bedDetailsList = bedDetailsService.list(queryWrapper);

            List<Map<String, Object>> result = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (BedDetails bd : bedDetailsList) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", bd.getId());
                item.put("bedId", bd.getBedId());

                // 查询 Bed 实体获取楼号、床位号和房间号
                Bed bed = bedService.getById(bd.getBedId());
                if (bed != null) {
                    item.put("buildingNo", bed.getBuildingNo());
                    item.put("bedNo", bed.getBedNo());
                    item.put("roomNo", bed.getRoomNo());
                }

                Customer customer = customerService.getById(bd.getCustomerId());
                if (customer != null) {
                    item.put("customerName", customer.getCustomerName());
                    item.put("customerAge", customer.getCustomerAge());
                    item.put("customerSex", customer.getCustomerSex());
                    item.put("idcard", customer.getIdcard());
                }
                if (bd.getStartDate() != null) {
                    item.put("startDate", sdf.format(bd.getStartDate()));
                }
                if (bd.getEndDate() != null) {
                    item.put("endDate", sdf.format(bd.getEndDate()));
                }
                result.add(item);
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取床位历史详情时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    // 分页查询（可选，方便前端分页展示）
    @GetMapping("/page")
    public ResponseEntity<?> getBedPage(@RequestParam int pageNum, @RequestParam int pageSize) {
        try {
            Page<Bed> page = new Page<>(pageNum, pageSize);
            bedService.page(page);
            return ResponseEntity.ok(page);
        } catch (Exception e) {
            logger.error("分页查询床位时发生错误", e);
            return ResponseEntity.internalServerError().build();
        }
    }









    @RequestMapping("get_all_building")
    public String getAllBuilding(){
        try {
            List<Bed> list = bedService.get_all_building();
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    @RequestMapping("get_all_room")
    public String getAllRoom(){
        try {
            List<Bed> list = bedService.get_all_building();
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("get_all_bed")
    public String getAllBed(){
        try {
            List<Bed> list = bedService.get_all_building();
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }



    @RequestMapping("getroom_by_building")
    public String getRoomByBuilding(@RequestParam("buildingNo") Integer buildingNo){
        try {
            List<Bed> list = bedService.getroom_by_building(buildingNo);
            System.out.println(list);
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    @RequestMapping("getbed_by_buildingroom")
    public String getRoomByBuildingRom(@RequestParam("buildingNo") Integer buildingNo,@RequestParam("roomNo") Integer roomNo){
        try {
            List<Bed> list = bedService.getbed_by_buildingroom(buildingNo,roomNo);
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
//    @PostMapping("getbed_by_buildingroom")
//    public String getRoomByBuildingRom(@RequestBody Map<Object, Object> params){
//        try {
//            Integer buildingNo = (Integer) params.get("buildingNo");
//            Integer roomNo = (Integer) params.get("roomNo");
//            List<Bed> list = bedService.getbed_by_buildingroom(buildingNo,roomNo);
//            return jsonReturn.returnSuccess(list);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
}